<template>
  <div class="modify_box">
    <el-card class="box-card">
      <div style="display: flex">
        <el-link type="primary" href="/nav" style="font-size: 16px">返回</el-link>
      </div>
      <el-header>
        <h2>修改密码</h2>
      </el-header>
      <el-form :model="form" ref="formRef" class="login-form" label-position="top">
        <el-form-item label="旧密码" prop="oldPassword">
          <el-input v-model="form.oldPassword" type="password" placeholder="请输入密码"></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="form.newPassword" type="password" placeholder="请再次输入密码"></el-input>
        </el-form-item>
      </el-form>
      <el-button type="primary" :disabled="!isFormValid" @click="onChangePassword" style="width: 100%; margin-top: 12px; height: 38px">修改密码</el-button>
    </el-card>
  </div>
</template>

<script setup>
import {computed, ref} from "vue";
import {logout, updatePwd} from "@/api/login";
import {ElMessage} from "element-plus";
import router from "@/router";
import Cookies from "js-cookie";
const formRef = ref(null);

const form = ref({
  newPassword: '',
  oldPassword: ''
});

const isFormValid = computed(() => {
  return (
      form.value.oldPassword.length > 0 &&
      form.value.newPassword.length > 0
  );
});

const onChangePassword = () => {
  updatePwd(form.value).then(res =>{
    if (res.code === 200){
      ElMessage.success('修改成功');
      logout().then(res =>{
        if (res.code === 200){
          Cookies.remove('token')
          router.push('/login')
          ElMessage.success('退出成功');
        }else {
          ElMessage.error(res.msg);
        }
      })
    }else {
      ElMessage.error(res.msg);
    }
  })
}

</script>

<style lang="less">
.modify_box {
  display: flex;
  align-items: center;
  height: 100%;
  padding: 0 8px;

  .box-card {
    width: 100%;

    .el-form-item__label {
      width: 100% !important;
      font-weight: bold !important;
      font-size: 17px;
      color: #000;
    }

  }
}
</style>
